package com.jxnu.nav_search.viewModels;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.jxnu.nav_search.database.SuggestionsSQLiteOpenHelperUtils;
import com.jxnu.nav_search.utils.Datasets;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.lifecycle.ViewModel;

/**
 * 定义数据的操作
 */
public class ScrollAcViewModel extends ViewModel {

    static Map<String, String> headers = new HashMap<String, String>() {{
        put("Content-Type", "application/x-www-form-urlencoded");
    }};

    public List<String> getRecyclerData() {

        final List<String> list = new ArrayList<>();
        Document document = null;
        try {
            document = Jsoup.connect("https://baike.baidu.com/item/%E6%A0%91%E5%8F%B6/2739940").get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        list.add(document.html());

        return list;
    }

    public static List<Datasets> getQuery(String query) throws UnsupportedEncodingException {

        List<Datasets> list = null;
        String url = "https://api.tianapi.com/txapi/lajifenlei/index?key=d1cea6184de09cf3c0f88183cb91d308&word=" +
                URLEncoder.encode(query, "UTF-8");
        Connection connection = Jsoup.connect(url);
        connection.ignoreContentType(true);
        try {
            Document document = connection.get();
            if (JsonParser.parseString(document.text()).getAsJsonObject().get("code").toString().equals("200")) {
                Gson gson = new Gson();
                list = gson.fromJson(JsonParser.parseString(document.text()).getAsJsonObject().get("newslist"), new TypeToken<List<Datasets>>() {
                }.getType());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return list;
        }
    }


    public Cursor getSuggestion(Context context) {
        ContentValues cv = new ContentValues();
        cv.put("name", "peter");
        cv.put("age", 26);
        cv.put("sex", "boy");

        SuggestionsSQLiteOpenHelperUtils suggestionsSQLiteOpenHelperUtils = new SuggestionsSQLiteOpenHelperUtils(context);
        suggestionsSQLiteOpenHelperUtils.createDB();
        suggestionsSQLiteOpenHelperUtils.insert(cv);


//        db.insert(SuggestionsSQLiteOpenHelper.TABLE_NAME, null, cv);

        return suggestionsSQLiteOpenHelperUtils.selectAll();
    }
}
